package com.koron.css2.clientCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.clientCenter.Enum.ProcessStateEnum;
import com.koron.css2.clientCenter.bean.UserInfoSplit;
import com.koron.css2.clientCenter.bean.UserInfoSplitDetail;
import com.koron.css2.clientCenter.mapper.UserInfoSplitDetailMapper;
import com.koron.css2.clientCenter.mapper.UserInfoSplitMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Date;
import java.util.List;

public class UserInfoSplitInsert implements ServerInterface {
    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            UserInfoSplit userInfoSplit = JsonUtils.objectToPojo(req.getData(), UserInfoSplit.class);
            UserInfoSplitMapper userInfoSplitMapper = factory.getMapper(UserInfoSplitMapper.class);
            UserInfoSplitDetailMapper userInfoSplitDetailMapper = factory.getMapper(UserInfoSplitDetailMapper.class);

            // 1. userInfoSplit: id, createAccount,createName,createAccount,tenantId
            userInfoSplit.setCreateInfo(userInfo);
            // 2. userInfoSplit：billNo
            String billNo = Tools.getBillNo(factory, "user_info_split", userInfo.getCurWaterCode());
            userInfoSplit.setBillNo(billNo);
            // 3. userInfoSplit: billDate
            userInfoSplit.setBillDate(new Date());
            // 4. userInfoSplit: processState, processName
            userInfoSplit.setProcessStateName(ProcessStateEnum.DRAFT.getState());
            userInfoSplit.setProcessName(ProcessStateEnum.DRAFT.getName());
            // 5. 新增userInfoSplit
            userInfoSplitMapper.insert(userInfoSplit);
            // 6. userInfoSplitDetail
            List<UserInfoSplitDetail> userInfoSplitDetailList = userInfoSplit.getUserInfoSplitDetailList();
            userInfoSplitDetailList.forEach(userInfoSplitDetail -> {
                // 6.1 id，createAccount,createTime,createName
                userInfoSplitDetail.setCreateInfo(userInfo);
                // 6.2 splitCode
                userInfoSplitDetail.setSplitCode(billNo);
                // 6.3 新增数据
                userInfoSplitDetailMapper.insert(userInfoSplitDetail);
            });

            // 7. 返回数据
            MessageBean<UserInfoSplit> messageBean = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "拆户新增成功", UserInfoSplit.class);
            messageBean.setData(userInfoSplit);
            return messageBean;
        } catch (Exception e) {
            logger.error("拆户新增失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "拆户新增失败", null);
        }
    }
}
